package com.jiubanqingchen.future.org.interceptor;

import com.jfinal.aop.Aop;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jiubanqingchen.future.common.enums.SystemStatus;
import com.jiubanqingchen.future.model.models.User;
import com.jiubanqingchen.future.org.admin.BaseController;
import com.jiubanqingchen.future.org.annotation.AuthorityKey;
import com.jiubanqingchen.future.org.authority.user.UserAuthorityService;
import com.jiubanqingchen.future.org.business.anonymous.AnonymousService;

/**
 * 权限拦截器
 */
public class AuthorityInterceptor implements Interceptor {

    @Override
    public void intercept(Invocation inv) {
        BaseController controller = (BaseController) inv.getController();
        AnonymousService anonymousService = Aop.get(AnonymousService.class);
        boolean isAnonymous = anonymousService.judgeIsAnonymous(inv.getActionKey());
        if (!isAnonymous) {
            User user = controller.getSessionAttr("currentUser");
            if (user == null) controller.renderResult(SystemStatus.LOGOUT);

            if (!controller.getClass().isAnnotationPresent(AuthorityKey.class)) {
                controller.renderResult(SystemStatus.ERROR_AUTHORITY, "controller未加AuthorityKey注解");
                return;
            }

            String controllerKey = controller.getClass().getAnnotation(AuthorityKey.class).value();
            AuthorityKey authorityKey = inv.getMethod().getAnnotation(AuthorityKey.class);
            if (authorityKey == null) {
                controller.renderResult(SystemStatus.ERROR_AUTHORITY, "method未加AuthorityKey注解");
                return;
            }

            String methodKey = authorityKey.value();
            UserAuthorityService userAuthorityService = Aop.get(UserAuthorityService.class);
            boolean flag = userAuthorityService.judgeAuthority(user.getUserId(), controllerKey + ":" + methodKey);
            if (!flag) {
                controller.renderResult(SystemStatus.ERROR_AUTHORITY, "无权限");
                return;
            }
        }
        inv.invoke();
    }
}
